// pages/weather.js
import indexApi from '../../api/index'

Page({

  data: {
    weatherInfo: {},
    futureList: {},
    cityList: ['沈阳市', '北京市', '上海市', '深圳市', '杭州市', '天津市', '南京市', '鞍山市', '武汉市', '成都市'],
    selectCity: 0,
    futureList: []
  },

  onLoad() {
    this.getWeather()
  },

  /**
   * 监听用户下拉动作
   */
  onPullDownRefresh() {
    getWeather()
  },
  async getWeather() {
    const cityList = this.data.cityList;
    const selectCity = this.data.selectCity;
    const city = cityList[selectCity].slice(0, cityList[selectCity].length - 1)
    const res = await indexApi.getWeather({ key: '6686c27e91ee031325039802a38148a6', city })
    if (res.data.error_code === 0) {
      const weatherInfo = res.data.result.realtime;
      const futureList = res.data.result.future;
      futureList.forEach(item => {
        item.temperature = item.temperature.slice(0, item.temperature.length - 1).split('/');
        item.date = item.date.split('-');
      })
      this.setData({ weatherInfo, futureList })
    } else {
      wx.showToast({
        title: res.data.reason,
        icon: 'none',
        duration: 2000
      });
      this.setData({
        weatherInfo: {},
        futureList: []
      })
    }
  },
  bindPickerChange(e) {
    this.setData({
      selectCity: e.detail.value
    });
    this.getWeather()
  },
})